package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private  WorkspaceServiceImpl  workspaceService;

    @Override
    public TurnoverReportVO GetTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getTurnoverByMap(map);
            turnoverList.add(turnover == null ? 0.0 : turnover);

        }
        return  TurnoverReportVO
                .builder()
                .dateList(StringUtils.join( datelist, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

    }

    @Override
    public OrderReportVO GetOrderStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        //获取订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer orderCount = orderMapper.getOrderByMap(map);
            orderCountList.add(orderCount == null ? 0 : orderCount);
        }
        //总的订单数
        Integer totalOrderCount = orderMapper.getOrderByMap(null);
        //获取有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderByMap(map);
            validOrderCountList.add(validOrderCount == null ? 0 : validOrderCount);
        }
        //获取总有效订单数
        Map<String, Object> map = new HashMap<>();
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = orderMapper.getOrderByMap(map);
        //订单完成率
        Double orderCompletionRate =validOrderCount * 1.0 / totalOrderCount;

        return  OrderReportVO
                .builder()
                .dateList(StringUtils.join( datelist, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public UserReportVO GetUserStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        //获取新增用户数列表
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer newUserCount = userMapper.getByDate(map);
            newUserList.add(newUserCount == null ? 0 : newUserCount);
        }
        //获取每天总用户数列表
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("end", endTime);
            Integer totalUserCount = userMapper.getByDate(map);
            totalUserList.add(totalUserCount == null ? 0 : totalUserCount);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join( datelist, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public SalesTop10ReportVO GetSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        for(GoodsSalesDTO goodsSalesDTO : salesTop10){
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber().toString());
        }

        return  SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //1.获取营业数据--30天的数据
        LocalDate datebegin = LocalDate.now().minusDays(30);
        LocalDate dateend = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(datebegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateend, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);


        //2.通过poi 生成excel文件

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于模板文件创建excel
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            //填充概览数据
            //获取sheet
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(datebegin + "至" + dateend);
            //获取第4行
            XSSFRow row =sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获取第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            // 填充明细数据
            for(int i = 0; i < 30; i++){
                LocalDate date = datebegin.plusDays(i);
               BusinessDataVO  businessdata = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
               // 获取行
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                // 判空处理，避免 NullPointerException
                row.getCell(2).setCellValue(businessdata.getTurnover() == null ? 0.0 : businessdata.getTurnover());
                row.getCell(3).setCellValue(businessdata.getValidOrderCount() == null ? 0 : businessdata.getValidOrderCount());
                row.getCell(4).setCellValue(businessdata.getOrderCompletionRate() == null ? 0.0 : businessdata.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessdata.getUnitPrice() == null ? 0.0 : businessdata.getUnitPrice());
                row.getCell(6).setCellValue(businessdata.getNewUsers() == null ? 0 : businessdata.getNewUsers());

            }

            //3.通过输出流将excel文件下载到浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //释放资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }




    }
}
